//
//  NextViewController.m
//  ZJControlsClass
//
//  Created by apple on 2024/10/26.
//

#import "NextViewController.h"
#import "AppDelegate.h"



#import "HomeZJLoginPublicApiManager.h"
#import "UserAgreementViewController.h"
#import <SangforSDK/SFUemSDK.h>




@interface NextViewController ()

@property (nonatomic,strong) UIView * follewView;
@property (nonatomic,strong) UIImageView * img;

@property (nonatomic,strong) UILabel * titileLabel;
@property (nonatomic,strong) UILabel * msgLabel;
@property (nonatomic,strong) UILabel * msgTwoLabel;






@property (nonatomic,strong) UIView * infoView;
@property (nonatomic,strong) UILabel * phoneLabel;
@property (nonatomic,strong) UIImageView * codeImg;
@property (nonatomic,strong) UILabel * codeLabel;
@property (nonatomic,strong) UITextField * codeTextF;
@property (nonatomic,strong) UIButton * getCodeBtn;
@property (nonatomic,strong) UIView * v;




@property (nonatomic,strong) UIButton * popBtn;
@property (nonatomic,strong) UIButton *loginBtn;



@property (nonatomic,strong) HomeZJLoginPublicApiManager * manager;
@property (nonatomic,strong) NSMutableDictionary * visitListDic;




@end

@implementation NextViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self startAutoTicket];
    [MBProgressHUD hideHUDForView:self.view animated:true];
    
}

- (void)startAutoTicket {
    /**
     * 这里是自动免密认证接口，返回true表示认证成功，此时用户就可以进行资源访问了，
     * 如果返回false,表示当前不满足自动免密条件，需要用户主动调用用户名密码认证接口
     */
//    if ([[SFUemSDK sharedInstance] startAutoTicket]) {
//        [LUtilityTools showAlertWithTitle:@"" message:@"免密认证成功" buttonAction:^{
//            [self showTestList];
//        }];
//    }
}



- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
//    [[SFUemSDK sharedInstance] setAuthResultDelegate:self];

    
    [self setUpUI];
//    [self respondsTo_getCode];
    [self.getCodeBtn setCountDownTotalTime:60 attributeString:YES formate:@"已发送%s" highLightColor:0];
}


-(void)setUpUI{
    [self.view addSubview:self.follewView];
    [self.follewView addSubview:self.titileLabel];
    [self.follewView addSubview:self.img];
    [self.follewView addSubview:self.msgLabel];
    [self.follewView addSubview:self.msgTwoLabel];
    
    
    [self.view addSubview:self.infoView];
    [self.view addSubview:self.phoneLabel];
    [self.view addSubview:self.codeImg];
    [self.view addSubview:self.codeLabel];
    [self.view addSubview:self.codeTextF];
    [self.view addSubview:self.getCodeBtn];
    [self.view addSubview:self.v];
    
    
    
    [self.infoView addSubview:self.popBtn];
    [self.infoView addSubview:self.loginBtn];
    
    
    
    
    [self.titileLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset([[UIApplication sharedApplication]statusBarFrame].size.height);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@(44));
    }];
    
    [self.img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(self.follewView);
        make.size.equalTo(@(CGSizeMake(ALIGN_HEIGHT_PT(214), ALIGN_HEIGHT_PT(214))));
    }];
    
    [self.msgLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.follewView).with.offset(ALIGN_WIDTH_PT(14));
        make.top.equalTo(self.titileLabel.mas_bottom).with.offset(ALIGN_HEIGHT_PT(32));
    }];
    
    [self.msgTwoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.follewView).with.offset(ALIGN_WIDTH_PT(14));
        make.top.equalTo(self.msgLabel.mas_bottom).with.offset(ALIGN_HEIGHT_PT(5));
    }];
    
    [self.infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.follewView.mas_bottom).with.offset(-ALIGN_HEIGHT_PT(20));
        make.bottom.equalTo(self.view.mas_bottom).with.offset(ALIGN_HEIGHT_PT(20));
    }];
    
    [self.phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.infoView).with.offset(ALIGN_WIDTH_PT(20));
        make.top.equalTo(self.infoView).with.offset(ALIGN_HEIGHT_PT(30));
    }];
    
    [self.codeImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.infoView).with.offset(ALIGN_WIDTH_PT(20));
        make.top.equalTo(self.phoneLabel.mas_bottom).with.offset(ALIGN_HEIGHT_PT(25));
        make.size.equalTo(@(CGSizeMake(ALIGN_WIDTH_PT(20), ALIGN_WIDTH_PT(20))));
    }];
    
    [self.codeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.codeImg.mas_centerY);
        make.left.equalTo(self.codeImg.mas_right).with.offset(ALIGN_WIDTH_PT(5));
    }];
    
    [self.codeTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.codeImg.mas_left);
        make.top.equalTo(self.codeImg.mas_bottom).with.offset(ALIGN_HEIGHT_PT(5));
        make.right.equalTo(self.infoView).with.offset(ALIGN_WIDTH_PT(-100));
        make.height.equalTo(@(ALIGN_HEIGHT_PT(45)));
    }];
    
    [self.getCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.infoView).with.offset(-ALIGN_WIDTH_PT(20));
        make.centerY.equalTo(self.codeTextF.mas_centerY);
        make.size.equalTo(@(CGSizeMake(ALIGN_WIDTH_PT(80), ALIGN_HEIGHT_PT(28))));
    }];
    
    [self.v mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.infoView).with.offset(ALIGN_WIDTH_PT(14));
        make.right.equalTo(self.infoView).with.offset(-ALIGN_WIDTH_PT(14));
        make.top.equalTo(self.codeTextF.mas_bottom);
        make.height.equalTo(@(1));
    }];
    
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.infoView).with.offset(ALIGN_WIDTH_PT(12));
        make.right.equalTo(self.infoView).with.offset(-ALIGN_WIDTH_PT(12));
        make.bottom.equalTo(self.infoView.mas_bottom).with.offset(-ALIGN_HEIGHT_PT(40));
        make.height.equalTo(@(ALIGN_HEIGHT_PT(45)));
    }];
    
    [self.popBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.infoView.mas_centerX);
        make.bottom.equalTo(self.loginBtn.mas_top).with.offset(-ALIGN_HEIGHT_PT(10));
        make.size.equalTo(@(CGSizeMake(100, 40)));
    }];
    
    
    
}
#pragma mark -- 点击事件

-(void)respondsTo_getCode{ // 获取验证码
    
    [[SFUemSDK sharedInstance].auth regetSmsCode:^(SFSmsMessage * _Nullable message, NSError * _Nullable error) {
        if (!error) {
            
            [self.getCodeBtn setCountDownTotalTime:60 attributeString:YES formate:@"已发送%s" highLightColor:0];
            
            
        }
    }];
    

    
    
}


-(void)respondsTo_popViewController{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)respondsTo_loginBtnViewController{
    
    if (self.codeTextF.text.length != 6){
        [MBProgressHUD showError:@"请填写验证码"];
        return;
    }
        //    [[SFUemSDK sharedInstance] doSecondaryAuth:SFAuthTypeSMS data:@{kAuthKeySMS:self.codeTextF.text}];
            [[SFUemSDK sharedInstance] doSecondaryAuth:SFAuthTypeSMS data:@{kAuthKeySMS:self.codeTextF.text}];//            NSURL *vpnUrl = [NSURL URLWithString:@"https://kzqtxzvpn.caacsri.com:9998"];

        //        NSString *username = @"U202409240001";
        //        NSString *username = self.phoneStr;w
        //        NSString *password = self.passwordStr;
                /**
                 * 开始用户名密码认证，认证结果会在认证回调onAuthSuccess,onAuthFailed,onAuthProgress中返回
                 */
        //        [[SFUemSDK sharedInstance] startPasswordAuth:vpnUrl userName:username password:password];

        //        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

#pragma mark - 跳转到业务界面
- (void)showTestList {
    /**
     * 表示认证成功，VPN和沙箱能力都已经准备好了，可以跳到您的业务界面，此Demo的业务界面为TestListViewController
     */
//    AppDelegate * Appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    [Appdelegate ToTabbar];
    
    self.visitListDic = @{}.mutableCopy;
    [self.visitListDic setValue:self.phoneStr forKey:@"username"];
    [self.visitListDic setValue:self.passwordStr forKey:@"password"];
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"正在加载...";
    [hud removeFromSuperViewOnHide];
    
    [self.manager dispatchTaskWithParam:self.visitListDic completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [hud hideAnimated:YES];
        
        if (responseObject && [responseObject[@"code"] integerValue] == 200) {
            // 请求成功 保存数据
            SaUserInfoCenter *info = [SaUserInfoCenter mj_objectWithKeyValues:responseObject[@"data"]];
            NSLog(@"%@ ==== %@", [SaUserInfoCenter shareInstance], info);
            [[SaUserInfoCenter shareInstance] configData:info];
            /* FMDB有错 空了可以打开看下sql语句 */
//            SaUserDataCenter * userData = [SaUserDataCenter shareIntance];
//            userData.accessToken = info.accessToken;
//            userData.userId = info.userId;
//            userData.expiresTime = info.expiresTime;
//            userData.refreshToken = info.refreshToken;
//            userData.isLogin = YES;
//            if ([userData save]) {
//
//                AppDelegate * Appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//                [Appdelegate ToTabbar];
//            }
            
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:info.accessToken forKey:@"accessToken"];
            [defaults setObject:info.refreshToken forKey:@"refreshToken"];
            [defaults setObject:info.expiresTime forKey:@"expiresTime"];
            [defaults setObject:@(info.userId) forKey:@"userId"];
            [defaults setObject:@(1) forKey:@"isLogin"];
            AppDelegate * Appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [Appdelegate ToTabbar];
            
            
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:responseObject[@"msg"] buttonAction:^{
                
            }];
        }

    }];
}

/**
 * 认证成功的回调
 * @param msg 认证成功的信息
 */
- (void)onAuthSuccess:(BaseMessage *)msg {
    NSLog(@"SecondAuthViewController onLoginSuccess");
    [self saveLoginInfo];
    
//    if (![[[SFUemSDK sharedInstance].config getOption:SFSDKOptionUsingSdkRandCodeUI] boolValue] && [self.navigationController.topViewController isKindOfClass:[SFRandCodeSdpViewController class]]) {
//        SFRandCodeSdpViewController *vc = (SFRandCodeSdpViewController *)self.navigationController.topViewController;
//        [vc.navigationController popViewControllerAnimated:YES];
//    }
    
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
//    [AlertUtil showAlert:@"" message:@"认证成功" completion:^{
//        [self showTestList];
//    }];
    [LUtilityTools showAlertWithTitle:@"温馨提示" message:@"认证成功" buttonAction:^{
        [self showTestList];
    }];
    
    
}


#pragma mark -- SFAuthResultDelegate

- (void)onAuthFailed:(SFBaseMessage *)message {
    [MBProgressHUD hideHUDForView:self.view];
    [LUtilityTools showAlertWithTitle:@"温馨提示" message:message.errStr buttonAction:^{
        
    }];
}


#pragma mark - SFAuthResultDelegate

- (BOOL)recoverLoginInfo {		
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *url = [defaults valueForKey:@"url"];
    if (url.length == 0) {
        return NO;
    }
    
//    self.pAddrTextField.text = url;
//    self.userNameLabel.text = [defaults valueForKey:@"username"];
//    self.passwordLabel.text = [defaults valueForKey:@"password"];
    return YES;
}

- (void)saveLoginInfo {
//    NSString *url = self.pAddrTextField.text;
    NSString *username = self.phoneStr;
//    NSString *password = self.passwordLabel.text;
    
//    if (url.length == 0) {
//        return;
//    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:url forKey:@"url"];
    [defaults setObject:username forKey:@"username"];
//    [defaults setObject:password forKey:@"password"];
    
    [defaults synchronize];
}



#pragma mark -- 懒加载
-(UIView *)follewView{
    if (!_follewView) {
        _follewView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ALIGN_HEIGHT_PT(260))];
        // gradient
        CAGradientLayer *gl = [CAGradientLayer layer];
        gl.frame = CGRectMake(0,0,SCREEN_WIDTH,260);
        gl.startPoint = CGPointMake(0.76, 0.5);
        gl.endPoint = CGPointMake(0.24, 0.5);
        gl.colors = @[(__bridge id)COLOR_RGB(102, 151, 246).CGColor,(__bridge id)COLOR_RGB(50, 113, 237).CGColor];
        gl.locations = @[@(0), @(1.0f)];
        [_follewView.layer addSublayer:gl];
    }
    return _follewView;
}

-(UIImageView *)img{
    if (!_img) {
        _img = [UIImageView new];
        _img.image = [UIImage imageNamed:@"Mask group"];
    }
    return _img;
}

-(UILabel *)titileLabel{
    if (!_titileLabel) {
        _titileLabel = [UILabel new];
        _titileLabel.text = @"登录";
        _titileLabel.textColor = [UIColor whiteColor];
        _titileLabel.textAlignment = NSTextAlignmentCenter;
        _titileLabel.font = FONT18;
    }
    return _titileLabel;
}

-(UILabel *)msgLabel{
    if (!_msgLabel){
        _msgLabel = [UILabel new];
        _msgLabel.text = @"欢迎使用，";
        _msgLabel.font = FONT18;
        _msgLabel.textAlignment = NSTextAlignmentLeft;
        _msgLabel.textColor = [UIColor whiteColor];
    }
    return  _msgLabel;
}

-(UILabel *)msgTwoLabel{
    if (!_msgTwoLabel){
        _msgTwoLabel = [UILabel new];
        _msgTwoLabel.text = @"机场数字通行证系统";
        _msgTwoLabel.font = FONT16;
        _msgTwoLabel.textAlignment = NSTextAlignmentLeft;
        _msgTwoLabel.textColor = [UIColor whiteColor];
    }
    return  _msgTwoLabel;
}


-(UIView *)infoView{
    if (!_infoView) {
        _infoView = [UIView new];
        _infoView.backgroundColor = [UIColor whiteColor];
        _infoView.layer.cornerRadius = 18;
        _infoView.layer.masksToBounds = YES;
    }
    return _infoView;
}

-(UILabel *)phoneLabel{
    if (!_phoneLabel){
        _phoneLabel = [UILabel new];
        _phoneLabel.textColor = [UIColor blackColor];
        _phoneLabel.font = FONT14;
        NSMutableString * str = [[NSMutableString alloc]initWithString:self.phoneStr];
//        [str replaceCharactersInRange:NSMakeRange(4, 4) withString:@"****"];
        _phoneLabel.text = [NSString stringWithFormat:@"手机号码：%@",str];
        _phoneLabel.textAlignment = NSTextAlignmentLeft;
    }
    return _phoneLabel;
}

-(UIImageView *)codeImg{
    if (!_codeImg){
        _codeImg = [UIImageView new];
        _codeImg.image = [UIImage imageNamed:@"验证码"];
    }
    return _codeImg;
}
-(UILabel *)codeLabel{
    if (!_codeLabel){
        _codeLabel = [UILabel new];
        _codeLabel.text = @"验证码";
        _codeLabel.textAlignment = NSTextAlignmentLeft;
        _codeLabel.font = FONT14;
        _codeLabel.textColor = [UIColor blackColor];
    }
    return _codeLabel;
}

-(UITextField *)codeTextF{
    if (!_codeTextF){
        _codeTextF = [UITextField new];
        _codeTextF.placeholder = @"请输入验证码";
        _codeTextF.textColor = [UIColor blackColor];
        _codeTextF.keyboardType = UIKeyboardTypeASCIICapableNumberPad;
        _codeTextF.font = FONT14;
    }
    return _codeTextF;
}

- (UIButton *)getCodeBtn{
    if (!_getCodeBtn){
        _getCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_getCodeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
        [_getCodeBtn setTitleColor:COLOR_RGB(50, 113, 237) forState:(UIControlStateNormal)];
        _getCodeBtn.titleLabel.font = FONT13;
        _getCodeBtn.layer.cornerRadius = 14;
        _getCodeBtn.layer.masksToBounds = YES;
        _getCodeBtn.layer.borderColor = COLOR_RGB(50, 113, 237).CGColor;
        _getCodeBtn.layer.borderWidth = 1;
        [_getCodeBtn addTarget:self action:@selector(respondsTo_getCode) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _getCodeBtn;
}

-(UIView *)v{
    if (!_v){
        _v = [UIView new];
        _v.backgroundColor = COLOR_RGB(217, 217, 217);
    }
    return _v;
}



-(UIButton *)popBtn{
    if (!_popBtn) {
        _popBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_popBtn setTitle:@"上一步" forState:UIControlStateNormal];
        [_popBtn setTitleColor:COLOR_RGB(50, 113, 237) forState:UIControlStateNormal];
        _popBtn.titleLabel.font = FONT14;
        [_popBtn addTarget:self action:@selector(respondsTo_popViewController) forControlEvents:UIControlEventTouchUpInside];
    }
    return _popBtn;
}

-(UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _loginBtn.titleLabel.font = FONT14;
        _loginBtn.backgroundColor = COLOR_RGB(50, 113, 237);
        _loginBtn.layer.cornerRadius = 10;
        _loginBtn.layer.masksToBounds = YES;
        [_loginBtn addTarget:self action:@selector(respondsTo_loginBtnViewController) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}
-(HomeZJLoginPublicApiManager *)manager{
    if (!_manager) {
        _manager = [HomeZJLoginPublicApiManager new];
    }
    return _manager;
}





@end
